package com.stx.boke.base.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;


//实现接口，实现数据库连接性，的连接性
public class BaseDao {
	private Connection conn;
	private String sql;
	private List<Object> param;

	// 不需要取值，只需要设值，用set方法
	public void setConn(Connection conn) {
		this.conn = conn;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public void setParam(List<Object> param) {
		this.param= param;
	}

	//设置参数
	public void setParamValue(PreparedStatement ps, List<Object> list) throws SQLException //预编译的statement对象，一个是list集合
	{
		for (int i = 0; i < list.size(); i++) {
			Object v = list.get(i);
			ps.setObject( i+1 , v);//下表从0开始
		}
		
	}
	//增删改方法的实现，应该返回int型
	public int executeUpdate() throws SQLException{
		int rowNumber =0;
		PreparedStatement psState=null;
		Statement state =null;
		ResultSet rs =null;
		try {//有参数的sql语句必须得用preparement（）得到
		if(param != null&&param.size()>0){
			psState=conn.prepareStatement(sql);
			setParamValue(psState,param);
			rowNumber=psState.executeUpdate();
		}else{//没有带参数的Sql语句用通用的state方法
			state = conn.createStatement();
			rowNumber = state.executeUpdate(sql);
		}
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			jdbcOracleUtil.free(rs, state, conn);
		}
		return rowNumber;
	}	
	//查询的方法
	public Result executeQuery() throws SQLException{
		Result result = null;
		PreparedStatement ps = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			if (param != null && param.size() > 0) {
				ps = conn.prepareStatement(sql);
				setParamValue(ps, param);
				rs = ps.executeQuery();
			} else {
				st = conn.createStatement();
				rs = st.executeQuery(sql);
			}
			result = ResultSupport.toResult(rs);
			//将resultset转化为result
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			jdbcOracleUtil.free(rs, st, conn);
		}
		return result;
	}
}